package com.morningstar.system.handler;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.morningstar.common.constants.BizConstants;
import com.morningstar.common.message.BaseMessage;
import com.morningstar.system.constants.MessageType;
import com.morningstar.system.constants.SendType;
import com.morningstar.system.dao.entity.SysMessage;
import com.morningstar.system.dao.entity.SysMessageTemplate;
import com.morningstar.system.service.SysMessageService;
import com.morningstar.system.service.SysMessageTemplateService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MessageHandler {

    @Resource
    private SysMessageService sysMessageService;

    @Resource
    private SysMessageTemplateService sysMessageTemplateService;

    public void handler(String message) {
        log.info("message:{}", message);
        BaseMessage baseMessage = JSON.parseObject(message, BaseMessage.class);
        String templateKey = baseMessage.getTemplateKey();
        SysMessageTemplate template = sysMessageTemplateService.getByTemplateKey(templateKey);
        if (template == null) {
            log.warn("templateKey:{} is not exist", templateKey);
            return;
        }
        if (CollUtil.isEmpty(template.getSendType())) {
            log.warn("templateKey:{} sendType is empty", templateKey);
            return;
        }
        // TODO 发送功能抽象成接口 并根据类型注册
        if (template.getSendType().contains(SendType.SMS)) {
            sendSms(baseMessage, template);
        }
        if (template.getSendType().contains(SendType.EMAIL)) {
            sendEmail(baseMessage, template);
        }
        if (template.getSendType().contains(SendType.SHORT_MESSAGE)) {
            sendShortMessage(baseMessage, template);
        }
    }

    /**
     * 发送站内消息
     *
     * @param baseMessage 消息实体
     * @param template      消息模板
     */
    private void sendSms(BaseMessage baseMessage, SysMessageTemplate template) {
        String templateContent = baseMessage.getMessageContent(template.getTemplateMessage());
        SysMessage sysMessage = new SysMessage();
        sysMessage.setUserId(baseMessage.getTargetUserId());
        sysMessage.setMessageTitle(baseMessage.getTitle());
        sysMessage.setMessageType(MessageType.MESSAGE.getType());
        sysMessage.setMessageContent(templateContent);
        sysMessage.setStatus(BizConstants.NO);
        sysMessageService.save(sysMessage);
    }

    /**
     * 发送邮件
     *
     * @param baseMessage 消息实体
     * @param template      消息模板
     */
    private void sendEmail(BaseMessage baseMessage, SysMessageTemplate template) {
    }

    /**
     * 发送短信
     *
     * @param baseMessage 消息实体
     * @param template      消息模板
     */
    private void sendShortMessage(BaseMessage baseMessage, SysMessageTemplate template) {
    }
}
